package com.bjtu.toyexchange;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.util.toyexchange.DialogUtil;
import com.util.toyexchange.HttpUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Gallery;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

/*
 * 用户注册
 * 包括选择头像，输入用户名、密码、密码确认、联系方式、地址
 */

public class RegisterActivity extends Activity {
	private AlertDialog dialog;
	private int photoPosition=0;
	private int[] photoesID={Const.ID_PHOTO_01,Const.ID_PHOTO_02,Const.ID_PHOTO_03,
				             Const.ID_PHOTO_04,Const.ID_PHOTO_05,Const.ID_PHOTO_06,
				             Const.ID_PHOTO_07,Const.ID_PHOTO_08,Const.ID_PHOTO_09,
				             Const.ID_PHOTO_10,Const.ID_PHOTO_11,Const.ID_PHOTO_12,};
	private String username, password, pwd_ag, phone_num, city, district, road, number, pro;
	private EditText en_name, en_pwd, en_pwd_ag, en_phone_num, en_city, en_district, en_road, en_number, en_add_det;
	private Button fanhui, register;
	private ImageButton ibtnPhoto;
	private Spinner provice;
	private ArrayAdapter adapter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		
		//单击ibtnPhoto时弹出对话框让用户选择头像
        ibtnPhoto=(ImageButton) findViewById(R.id.ib_photo);
        ibtnPhoto.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				dialog=getDialog();
				dialog.show();
			}
		});
		
		//返回的按钮
		fanhui = (Button)findViewById(R.id.reg_back_btn);
		fanhui.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				RegisterActivity.this.finish();
			}
		});
		
		//注册的按钮
		register = (Button)findViewById(R.id.btn_reg);
		register.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				getUserInfo();
				
				if (checkInfo()) {
					if (registerPro()) {
						Intent intent = new Intent();
//						//还有头像~！！
//						intent.putExtra("username", username);
//						intent.putExtra("password", password);
						intent.setClass(RegisterActivity.this, MainActivity.class);
						RegisterActivity.this.startActivity(intent);
						
						Toast.makeText(RegisterActivity.this, username+"，您已成功注册...", 200).show();
					}
				}
			}
		});
		
		provice = (Spinner)RegisterActivity.this.findViewById(R.id.sel_province);
		//将可选内容与ArrayAdapter连接起来
		adapter = ArrayAdapter.createFromResource(RegisterActivity.this, R.array.province_arr, 
				android.R.layout.simple_spinner_item);
		//设置下拉列表的风格
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		provice.setAdapter(adapter);
		//下拉菜单的事件监听器
		provice.setOnItemSelectedListener(new SpinnerXMLSelectedListener());
		provice.setVisibility(View.VISIBLE);
		
	}
	
	private void getUserInfo(){
		//得到用户输入的信息，如：用户名、密码等等
		en_name = (EditText)RegisterActivity.this.findViewById(R.id.en_username);
		username = en_name.getText().toString();
		
		en_pwd = (EditText)RegisterActivity.this.findViewById(R.id.en_password);
		password = en_pwd.getText().toString();
		
		en_pwd_ag = (EditText)RegisterActivity.this.findViewById(R.id.en_password_ag);
		pwd_ag = en_pwd_ag.getText().toString();
		
		en_phone_num = (EditText)RegisterActivity.this.findViewById(R.id.en_reg_way);
		phone_num = en_phone_num.getText().toString();
		
		en_city = (EditText)RegisterActivity.this.findViewById(R.id.en_city);
		city = en_city.getText().toString();
		
		en_district = (EditText)RegisterActivity.this.findViewById(R.id.distiact);
		district = en_district.getText().toString();
		
		en_road = (EditText)RegisterActivity.this.findViewById(R.id.road);
		road = en_road.getText().toString();
		
		en_number = (EditText)RegisterActivity.this.findViewById(R.id.number);
		number = en_number.getText().toString();
	}
	
	private boolean checkInfo() {
		//注册信息校验
		if (("").equals(username) || null == username) {
			Toast.makeText(RegisterActivity.this,"用户名不能为空...",100).show();
			return false;
		}
		else if (username.length() > 6 || username.length() < 3) {
			Toast.makeText(RegisterActivity.this,"用户名长度不符合要求...",100).show();
			return false;
		}
		else if (("").equals(password) || null == password) {
			Toast.makeText(RegisterActivity.this,"密码不能为空...",100).show();
			return false;
		}
		else if (password.length() > 8 || password.length() < 4) {
			Toast.makeText(RegisterActivity.this,"密码长度不符合要求...",100).show();
			return false;
		}
		else if (("").equals(pwd_ag) || null == pwd_ag) {
			Toast.makeText(RegisterActivity.this,"确认密码不能为空...",100).show();
			return false;
		}
		else if (!password.equals(pwd_ag)) {
			Toast.makeText(RegisterActivity.this,"两次输入密码不相同...",100).show();
			return false;
		}
		else if (("").equals(phone_num) || null == phone_num) {
			Toast.makeText(RegisterActivity.this,"手机号码不能为空...",100).show();
			return false;
		}
		else if (("").equals(city) || null == city) {
			Toast.makeText(RegisterActivity.this,"所在市不能为空...",100).show();
			return false;
		}
		else if (("").equals(district) || null == district) {
			Toast.makeText(RegisterActivity.this,"所在区不能为空...",100).show();
			return false;
		}
		else if (("").equals(road) || null == road) {
			Toast.makeText(RegisterActivity.this,"所在街道不能为空...",100).show();
			return false;
		}
		else if (("").equals(number) || null == number) {
			Toast.makeText(RegisterActivity.this,"街道号不能为空...",100).show();
			return false;
		}
		return true;
		
	}
	
	/**
	 * 注册
	 * @param userInfo
	 *（用户填写的用户）
	 * @throws Exception 
	 * @throws JSONException 
	 */
	private JSONObject register() throws JSONException, Exception {
		// 使用Map封装请求参数
		Map<String, String> map = new HashMap<String, String>();
		map.put("username", username);
		map.put("password", password);
		map.put("phone_num", phone_num);
		map.put("city", city);
		map.put("district", district);
		map.put("road", road);
		map.put("number", number);
		map.put("pro", pro);
		// 定义发送请求的URL
		String url = HttpUtil.BASE_URL + "RegisterServlet";
		// 发送请求
		
		JSONObject jb = new JSONObject(HttpUtil.postRequest(url, map));
		DialogUtil.showDialog(this, "register():registerId", false);
		return jb;
	}
	
	//注册信息
	private boolean registerPro()
		{
			JSONObject jsonObj;
			try
			{
				jsonObj = register();
				// 如果userId 大于0
				if (jsonObj.getInt("registerId") > 0)
				{
					DialogUtil.showDialog(this, "注册成功！", false);
					return true;
				}
				else
					DialogUtil.showDialog(this, "注册有误！", false);
			}
			catch (Exception e)
			{
//				DialogUtil.showDialog(this, "服务器响应异常，请稍后再试！", false);
				e.printStackTrace();
			}

			return false;
		}
	
	class SpinnerXMLSelectedListener implements OnItemSelectedListener{
		public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			pro = (String)adapter.getItem(arg2);
		}
		public void onNothingSelected(AdapterView<?> arg0) {
			
		}
	}
	
    //创建一个对话框
    private AlertDialog getDialog(){
    	return new AlertDialog.Builder(this).setTitle("请选择您喜欢的头像哈~").setView(getDialogView())
    	 	       .setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							ibtnPhoto.setImageResource(photoesID[photoPosition]);
						}
				    }).setNegativeButton("取消", null) .create();
    }
    
    //创建对话框AlertDialog中的控件
    private View getDialogView(){
    	View view=LayoutInflater.from(this).inflate(R.layout.select_touxiang, null);
    	Gallery gallery=(Gallery) view.findViewById(R.id.alertdialog_layout_gallery);
    	GalleryAdapter adapter=new GalleryAdapter(this, photoesID);
    	gallery.setAdapter(adapter);
    	final ImageView ivShowPhoto=(ImageView) view.findViewById(R.id.alertdialog_layout_iv);
    	ivShowPhoto.setImageResource(photoesID[0]);
    	//单击gallery上的某一项item时，在imageview中加强显示
    	gallery.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ivShowPhoto.setImageResource(photoesID[position%photoesID.length]);
				photoPosition=position%photoesID.length;
			}
		});
    	return view;	
    }

}
